// import createEventHub from "ynw/createEventHub";
import createEventHub from "./createEventHub";
const hub = createEventHub();
const REMOTE_DATA = "REMOTE_DATA";
import dayjs from "dayjs";
// Web端调试不向客户端发送请求
const isWeb = /isWeb/.test(window.location.href);
const cache = {};
/**
 * 股票推送
 * @param {*} id
 * @param {*} data
 * @param {*} callback
 */
export function stockPush({ id, codes, source, callback }) {
  if (isWeb) return;
  if (!cache[id]) {
    cache[id] = source; //缓存
    hub.on(REMOTE_DATA, callback);
  }
  getDataFromClient(id, codes);
}

/**
 * 服务器推送
 */
window.remoteCallback = function(data) {
  if(!data) return;
  const arr = JSON.parse(window.atob(data));
  const id = arr.reqid;
  //和旧数据进行合并
  const source = cache[id];
  const final = [];
  arr.block.forEach((item, i) => {
    final.push({
      blockHotValue: source[i].newsInfoBlockFeeling.blockHotValue,
      blockFeelingsValue: source[i].newsInfoBlockFeeling.blockFeelingsValue,
      id: source[i].newsInfoBlockFeeling.id,
      brief: source[i].brief,
      newsInfoBlockFeeling: {
        blockCode: source[i].newsInfoBlockFeeling.blockCode,
        blockId: source[i].newsInfoBlockFeeling.blockId,
        chgRatio: item.chgRatio,
        chgRatioStr: item.chgRatio == 7654321 ? "--" : numberFormat(item.chgRatio) + "%",
        upNum: item.upNum,
        downNum: item.downNum,
        newsNum: source[i].newsNum,
        constituentStockNum: item.constituentStockNum,
        blockName: source[i].newsInfoBlockFeeling.blockName,
        color: {
          red: item.chgRatio > 0,
          green: item.chgRatio < 0,
        },
      },
      newInfoItemList: source[i].newInfoItemList.map((news) => {
        news.time = dayjs(new Date(news.publDate)).format("YYYY-MM-DD HH:mm");
        return news;
      }),
      
      stockList: item.stock.map((stock, j) => ({
        id: source[i].stockList[j].id,
        chgRatio: stock.chgRatio,
        chgRatioStr: stock.chgRatio == 7654321 ? "--" : numberFormat(stock.chgRatio) + "%",
        blockName: source[i].stockList[j].blockName,
        blockHotValue: source[i].stockList[j].blockHotValue,
        blockId: stock.stockId,
        color: {
          red: stock.chgRatio > 0,
          green: stock.chgRatio < 0,
        },
      })),
    });
  });
  hub.emit(REMOTE_DATA, { id, value: final });
};

/**
 * 查询客户端股票和板块数据
 * @param {Array} codes - 股票代码或板块代码
 */
function getDataFromClient(id, codes) {
  const t = Date.now();
  codes = JSON.stringify(codes);
  window.prompt(
    "",
    `up://["user.info",${t}, {"type":"get_data", "data": {"reqid":"${id}", "block": ${codes}, "callback": "remoteCallback" } }]`
  );
}

/**
 * 工具函数
 */
function returnFloat(value) {
  value = Math.round(parseFloat(value) * 100) / 100;
  if (String(value).indexOf(".") == -1) return value;
  const xsd = value.toString().split(".");
  if (xsd.length == 1) {
    value = value.toString() + ".00";
    return value;
  }
  if (xsd.length > 1) {
    if (xsd[1].length < 2) {
      value = value.toString() + "0";
    }
    return value;
  }
}


export function numberFormat(value) {
  if (!value) return "0";
  var param = {
    percent: value < 0 ? "-" : "",
    value: "",
    unit: "",
  };
  value = String(value).replace(/-/g, "");
  var k = 10000,
    sizes = ["", "万", "亿", "万亿"],
    i;

  if (value < k) {
    param.value = returnFloat(value);
  } else {
    i = Math.floor(Math.log(value) / Math.log(k));
    param.value = returnFloat(value / Math.pow(k, i));
    param.unit = sizes[i];
  }
  return `${param.percent + param.value + param.unit}`;
}

export function imgPath(data) {
  const reg = /<img [^>]*src=['"]([^'"]+)[^>]*>/gi;
  var regExp = window.location.href;
  let urlPath = "";
  switch (true) {
    case /http:\/\/app-test.zx093.com/.test(regExp):
      urlPath = "http://product-test.zx093.com";
      break;
    case /http:\/\/app-dev.zx093.com/.test(regExp):
      urlPath = "http://product-dev.zx093.com";
      break;
    case /http:\/\/client.zx093.com/.test(regExp):
      urlPath = "http://product.zx093.com";
      break;
  }
  return data.replace(reg, (img, url) =>
    url.indexOf("http") != -1
      ? `<img src="${url}" onerror="this.src='${url}'"/>`
      : `<img src="${urlPath + url}" onerror="javascript:this.src='${urlPath + url}'"/>`
  );
}
